
package com.lh.testmusic.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

import com.lh.testmusic.entity.Song;
import com.lh.testmusic.ible.IMusic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 播放音乐的服务
 */
public class PlayService extends Service {
    private MediaPlayer player;
    private List<Song>  songList=new ArrayList<>();
    public PlayService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        play(0);
        return new PlayBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
    public void play(int position){
        if(position<0){
            position=songList.size();
        }
        player=new MediaPlayer();
        //当前要播放的歌曲
        Song currentSong=songList.get(position);
        Uri uri=Uri.parse(currentSong.getBitrate().getFile_link());
        try {
            player.setDataSource(this,uri);
            player.prepareAsync();
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    player.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public class PlayBinder extends Binder implements IMusic{

        @Override
        public void initMusic() {
            songList.clear();
            //添加所有的音乐
            //songList.addAll();
            play(0);
        }

        @Override
        public void startPlay() {
            if (player!=null&&!player.isPlaying()){
                player.start();
            }
        }

        @Override
        public void pausePlay() {
            if (player!=null&&player.isPlaying()){
                player.pause();
            }
        }

        @Override
        public void next() {

        }

        @Override
        public void prev() {

        }
    }
}
